package com.faradel.pharmapp.managedbean;

import java.io.Serializable;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.faradel.pharmapp.entities.PharmaUser;
import org.springframework.context.ApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

import com.faradel.pharmapp.service.ValidationServiceInterface;

/**
 * LoginBean.java
 * 
 */
@ManagedBean
@SessionScoped
public class LoginBean implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static final String SUCCESS = "mainhome";
    private String name;
    private String password;
    PharmaUser user;

    {
        ApplicationContext context = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        user = (PharmaUser) context.getBean("pharmaUser");
    }

    public String login()
    {
        user = getValidationServiceImpl().verifyUser(name, password);

        if (user != null)
        {
            ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
            Map<String, Object> sessionMap = extContext.getSessionMap();
            sessionMap.put("sessionUser", user);
            return SUCCESS;
        }
        else
        {
            FacesContext cxt = FacesContext.getCurrentInstance();
            cxt.addMessage("Username", new FacesMessage("Invalid User Name and Password Entered!!!"));
            return "index";
        }
    }

    public String logout()
    {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "index";
    }

    public String getName()
    {
        return name;
    }

    public void setName(final String name)
    {
        this.name = name;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(final String password)
    {
        this.password = password;
    }

    public ValidationServiceInterface getValidationServiceImpl()
    {
        ApplicationContext cxt = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        return (ValidationServiceInterface) cxt.getBean("validationServiceImpl");
    }

}